package com.hongsuan.pplive.front;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.util.AlipayNotify;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.cnjson.common.config.Global;
import com.cnjson.common.security.shiro.session.SessionDAO;
import com.cnjson.common.servlet.ValidateCodeServlet;
import com.cnjson.common.utils.CacheUtils;
import com.cnjson.common.utils.CookieUtils;
import com.cnjson.common.utils.IdGen;
import com.cnjson.common.utils.StringUtils;
import com.cnjson.common.web.BaseController;
import com.hongsuan.pplive.modules.live.entity.LivePresentRecord;
import com.hongsuan.pplive.modules.live.service.LivePresentRecordService;
import com.hongsuan.pplive.modules.sys.entity.User;
import com.hongsuan.pplive.modules.sys.security.FormAuthenticationFilter;
import com.hongsuan.pplive.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.hongsuan.pplive.modules.sys.service.SystemService;
import com.hongsuan.pplive.modules.sys.utils.UserUtils;

@Controller
public class FrontUserController extends BaseController {

	@Autowired
	private SessionDAO sessionDAO;

	@Autowired
	private LivePresentRecordService LivePresentRecordService;

	@Autowired
	private SystemService systemService;

	@RequestMapping(value = "/badRequest")
	public @ResponseBody Object badRequest(Integer code, String message) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("message", message);
		map.put("code", code);
		Gson gson = new Gson();
		return gson.toJson(map);
	}

	@RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
	public String toFront(HttpServletRequest request, HttpServletResponse response, Model model) {
		if (UserUtils.getPrincipal() == null) {
			return "redirect:/login";
		}
		if (UserUtils.isAdmin()) {
			return "redirect:" + adminPath;
		}
		model.addAttribute("message", "非法请求!");
		return "front/message";
	}

	private String encoder(String source) throws UnsupportedEncodingException {
		return new String(source.getBytes("ISO-8859-1"), "UTF-8");
	}

	@RequestMapping(value = "/alipay/notify_url", method = RequestMethod.GET)
	public void alipayNotifyUrl(HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, String> params = new HashMap<String, String>();
		Map<?, ?> requestParams = request.getParameterMap();
		for (Iterator<?> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		try {
			// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
			// 批量付款数据中转账成功的详细信息
			String success_details = encoder(request.getParameter("success_details"));
			// 批量付款数据中转账失败的详细信息
			String fail_details = encoder(request.getParameter("fail_details"));

			// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)
			String tradeNo = request.getParameter("out_trade_no");// 订单号
			String tradeStatus = request.getParameter("trade_status");// 交易状态
			LivePresentRecord record = LivePresentRecordService.findOneByLineNo(tradeNo);

			if (AlipayNotify.verify(params)) {
				if (tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
					// 判断是否在商户网站中已经做过了这次通知返回的处理
					record.setState(2);
					User user = UserUtils.get(record.getCreateById());
					float cutMoney = (user.getAccount() - record.getAmount());
					user.setAccount(cutMoney);
					systemService.updateUserAccount(user);
					logger.info(success_details);
					System.out.println("success");
				}
			} else {
				System.out.println("fail");
				logger.error(fail_details);
				record.setState(3);
			}
			LivePresentRecordService.save(record);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * To: goto loginPage author:ianhitlgang
	 */
	@RequestMapping(value = { "/login" }, method = RequestMethod.GET)
	public String toLoginPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		// Principal principal = UserUtils.getPrincipal();
		if (logger.isDebugEnabled()) {
			logger.debug("login, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}

		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
			CookieUtils.setCookie(response, "LOGINED", "false");
		}

		// 如果已经登录，则跳转到管理首页
		// if (principal != null && !principal.isMobileLogin()) {
		if (UserUtils.isAdmin()) {
			return "redirect:" + adminPath;
		}
		return "front/login";
	}

	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String loginFail(HttpServletRequest request, HttpServletResponse response, Model model) {
		// Principal principal = UserUtils.getPrincipal();

		// 如果已经登录，则跳转到管理首页
		// if (principal != null) {
		if (UserUtils.isAdmin()) {
			return "redirect:" + adminPath;
		}

		String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
		boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
		boolean mobile = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM);
		String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		String message = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);

		if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")) {
			message = "用户或密码错误, 请重试.";
		}

		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, rememberMe);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_MOBILE_PARAM, mobile);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, exception);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);

		if (logger.isDebugEnabled()) {
			logger.debug("login fail, active session size: {}, message: {}, exception: {}",
					sessionDAO.getActiveSessions(false).size(), message, exception);
		}

		// 非授权异常，登录失败，验证码加1。
		if (!UnauthorizedException.class.getName().equals(exception)) {
			model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(username, true, false));
		}

		// 验证失败清空验证码
		request.getSession().setAttribute(ValidateCodeServlet.VALIDATE_CODE, IdGen.uuid());

		// 如果是手机登录，则返回JSON字符串
		if (mobile) {
			return renderString(response, model);
		}

		// return "modules/sys/sysLogin";
		return "front/login";
	}

	/**
	 * 登录成功，进入管理首页
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "${adminPath}")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		Principal principal = UserUtils.getPrincipal();

		// 登录成功后，验证码计算器清零
		isValidateCodeLogin(principal.getLoginName(), false, true);

		if (logger.isDebugEnabled()) {
			logger.debug("show index, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}

		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
			String logined = CookieUtils.getCookie(request, "LOGINED");
			if (StringUtils.isBlank(logined) || "false".equals(logined)) {
				CookieUtils.setCookie(response, "LOGINED", "true");
			} else if (StringUtils.equals(logined, "true")) {
				UserUtils.getSubject().logout();
				return "redirect:/login";
			}
		}

		// 如果是手机登录，则返回JSON字符串
		if (principal.isMobileLogin()) {
			if (request.getParameter("login") != null) {
				return renderString(response, principal);
			}
			if (request.getParameter("index") != null) {
				return "modules/sys/sysIndex";
			}
			return "redirect:/login";
		}

		return "modules/sys/sysIndex";
	}

	/**
	 * 获取主题方案
	 */
	@RequestMapping(value = "/theme/{theme}")
	public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request,
			HttpServletResponse response) {
		if (StringUtils.isNotBlank(theme)) {
			CookieUtils.setCookie(response, "theme", theme);
		} else {
			theme = CookieUtils.getCookie(request, "theme");
		}
		return "redirect:" + request.getParameter("url");
	}

	/**
	 * 是否是验证码登录
	 * 
	 * @param useruame
	 *            用户名
	 * @param isFail
	 *            计数加1
	 * @param clean
	 *            计数清零
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean isValidateCodeLogin(String useruame, boolean isFail, boolean clean) {
		Map<String, Integer> loginFailMap = (Map<String, Integer>) CacheUtils.get("loginFailMap");
		if (loginFailMap == null) {
			loginFailMap = Maps.newHashMap();
			CacheUtils.put("loginFailMap", loginFailMap);
		}
		Integer loginFailNum = loginFailMap.get(useruame);
		if (loginFailNum == null) {
			loginFailNum = 0;
		}
		if (isFail) {
			loginFailNum++;
			loginFailMap.put(useruame, loginFailNum);
		}
		if (clean) {
			loginFailMap.remove(useruame);
		}
		return loginFailNum >= 3;
	}

}
